package model

import (
	"errors"
	"ip_server/db"
	"ip_server/service/param"
	"time"
)

// Log  分组
type Log struct {
	ID          int64  ` json:"id"`          // 组ID
	Fingerprint string ` json:"fingerprint"` // 组名称
	IP          string ` json:"ip"`          // 组名称
	Type        int    ` json:"type"`        // 组名称
	Region      string ` json:"region"`      // 组名称
	Label       string ` json:"label"`       // 组名称
	Reason      int    ` json:"reason"`      // 组名称
	CreatedAt   int64  ` json:"created_at"`  // 组名称
	UpdatedAt   int64  ` json:"updated_at"`  // 组名称
}

func (p Log) tableName() string {
	return "`log`"
}

// List 根据请求参数查询用户列表
func (g *Log) List(req param.LogsReqBefore) (total int, data []Log, err error) {

	if req.Page <= 0 {
		req.Page = 1
	}

	if req.PageSize <= 0 {
		req.PageSize = 10
	}
	// 计算偏移量
	offset := (req.Page - 1) * req.PageSize

	where := " where 1=1 " // 初始化SQL的WHERE子句

	// 查询总记录数
	err = db.DbWrapper.QueryRow("SELECT COUNT(*) FROM " + g.tableName()).Scan(&total)
	if err != nil {
		return
	}
	// 查询当前页数据
	// 查询当前页数据
	rows, err := db.DbWrapper.Query("SELECT id,fingerprint,ip,type,region,label,reason,created_at  FROM "+g.tableName()+where+" LIMIT ? OFFSET ?", req.PageSize, offset)

	if err != nil {
		return
	}
	defer rows.Close()
	res := make([]Log, 0)
	for rows.Next() {
		var proTemp Log
		rows.Scan(&proTemp.ID, &proTemp.Fingerprint, &proTemp.IP, &proTemp.Type, &proTemp.Region, &proTemp.Label, &proTemp.Reason, &proTemp.CreatedAt)
		res = append(res, proTemp)
	}
	return total, res, err // 返回查询到的数据和可能的错误
}

// Add ...
func (g *Log) Add(req *Log) error {
	sqlStr := "insert into " + g.tableName() + "(`fingerprint`,`ip`,`type`,`region`,`label`,`reason`,`created_at`)" +
		" values (?,?,?,?,?,?,?)"
	err := db.DbWrapper.Exec(sqlStr, req.Fingerprint, req.IP, req.Type, req.Region, req.Label, req.Reason, time.Now().Unix())
	return err
}

// Update ...
func (g *Log) Update(req *Log) error {
	//1、先查询
	count := g.InfoNum(req.ID)
	if count <= 0 {
		return errors.New("数据不存在")
	}
	// 以下为示例数据，根据实际情况进行修改
	id := req.ID
	// 构建更新语句和参数列表
	query := "UPDATE " + g.tableName() + " SET"
	args := []interface{}{}

	query += " fingerprint = ?,"
	args = append(args, req.Fingerprint)
	// 移除最后一个逗号
	query = query[:len(query)-1]

	query += " WHERE id = ?"
	args = append(args, id)

	// 执行更新
	return db.DbWrapper.Exec(query, args...)
}

// Delete 根据请求参数查询用户列表
func (g *Log) Delete(id interface{}) error {
	//1、先查询
	count := g.InfoNum(id)
	if count <= 0 {
		return errors.New("删除的数据不存在")
	}
	//2、再删除
	delStr := "delete from  " + g.tableName() + " where group_id=?"
	return db.DbWrapper.Exec(delStr, id)
}

// InfoNum 根据请求参数查询用户列表
func (g *Log) InfoNum(id interface{}) int {
	var count int
	//1、先查询
	sqlStr := "select count(*) from " + g.tableName() + " where id=?"
	err := db.DbWrapper.QueryRow(sqlStr, id).Scan(&count)
	if count <= 0 || err != nil {
		return 0
	}
	return count
}

// GetInfoByID  //通过ID获取信息
func (u *Log) GetInfoByID(id string) (proTemp Log, err error) {
	//1、先查询
	sqlStr := "select group_id, group_name " +
		" from " + u.tableName() + " where id =?"
	err = db.DbWrapper.QueryRow(sqlStr, id).Scan(&proTemp.ID, &proTemp.ID)
	return proTemp, err
}

// GetInfoByName  //通过ID获取信息
func (u *Log) GetInfoByName(field, value string) (proTemp Log, err error) {
	//1、先查询
	sqlStr := "select id " +
		" from " + u.tableName() + " where `" + field + "` =?"
	err = db.DbWrapper.QueryRow(sqlStr, value).Scan(&proTemp.ID)
	return proTemp, err
}
